<template>
	<view class="viewBg">
        <view>
            <map style="width: 100%; height: 600upx;" id="mapId"
                 :latitude="location.latitude"
                 :longitude="location.longitude"
                 :controls="mapControls"
                 :markers="covers"></map>
        </view>

		<view class="lyx-action">
			<view class="lya-action-top">打卡地点</view>
			<view>
				<view class="uni-flex" style="justify-content: space-between;" v-for="(item, index) in addressData" :key="index">
						<view v-if="state == 3" style="width: 80%;">
							<radio :value="index" :checked="current == item.id" @click="radioChange(item)"/>
							{{ item.address }}
						</view>
						<view v-if="state != 3" style="min-width: 160upx">{{ item.address }}</view>
						<view v-if="state == 1"><button class="mini-btn" type="warn" size="mini" @click="savePoitLock(index + 1)">设置</button></view>
						<view v-if="state == 2"><button class="mini-btn" type="warn" size="mini">审核中</button></view>
				</view>
			</view>
		</view>

		<view class="feedback-body feedback-uploader" v-if="state == 3">
			<view class="uni-uploader">
				<view class="uni-uploader-head">
					<view class="uni-uploader-title">点击上传图片</view>
					<view class="uni-uploader-info">{{ imageList.length }}/6</view>
				</view>
				<view class="uni-uploader-body">
					<view class="uni-uploader__files">
						<block v-for="(image, index) in imageList" :key="index">
							<view class="uni-uploader__file" style="position: relative;">
								<image class="uni-uploader__img" :src="image" @tap="previewImage(index)"></image>
								<view class="close-view" @click="close(index)">x</view>
							</view>
						</block>
						<view class="uni-uploader__input-box" v-show="imageList.length < 6"><view class="uni-uploader__input" @tap="chooseImg"></view></view>
					</view>
				</view>
			</view>
		</view>

		<view style="padding: 40upx;" v-if="state == 3"><button class="mini-btn" type="primary" @click="daka">打卡</button></view>
        <view style="padding: 40upx;" v-if="state == 1"><button class="mini-btn" type="primary" @click="saveDaKa">保存</button></view>

        <view class="resave-local" @click="setNewLocation" v-if="state==3">重新设置位置</view>
	</view>
</template>

<script>
import amap from '../../../common/amap-wx.js';
import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
import { preceedPointInArea } from '@/common/util.js';
export default {
	components: { mpvuePicker },
	data() {
		return {
			title: 'map',
			location: {},
			amapPlugin: null,
			mapKey: 'fbb5ddc12d6183eba23f27639f49757a',
			covers: [],
            mapControls: [{
                id: 2,
                position: {
                    left: 160,
                    top: 160,
                    width: 30,
                    height: 35
                },
                iconPath: '../../../static/img/location.png'
            }],
			list: [],
			addressData: [{ id: 1, address: '等待设置' },{ id: 2, address: '等待设置' },{ id: 3, address: '等待设置' }],
			state: 1, // 1- 没有设置地点，2-等待审核，3-审核通过
			imageList: [],
			upimageData:'',
			checkAddress: {}, //选中的打卡地址
			current: 0
		};
	},
	onLoad() {
		let that = this
		this.amapPlugin = new amap.AMapWX({
			key: this.mapKey
		});
		this.getLocation()
		this.setTime()
        this.setMapControls()
		this.locationList()
        //uni.removeStorageSync('addressjson')
	},
	methods: {
		setMapControls(){
			let that = this
            let mp = {
	            id: 2,
	            position: {
		            left: 160,
		            top: 160,
		            width: 30,
		            height: 35
	            },
	            iconPath: '../../../static/img/location.png'
            }
            uni.getSystemInfo({
                success: function(data) {
                    let height = data.screenHeight;
                    let width = data.screenWidth;
                    mp.position.left = width / 2;
                    mp.position.top = (300 / 2);
                    that.mapControls[0] = mp
                    console.log('屏幕宽度' + width + "ScreenWidth" + JSON.stringify(that.mapControls[0]));
                }
            })
        },
		setTime() {
			var that = this;
			setInterval(function() {
				that.getLocation();
			}, 3000);
		},
		getLocation() {
			var that = this;
			this.amapPlugin.getRegeo({
				success: data => {
					that.address = data[0].name;
					var time = that.getDate();
					var item = { address: data[0].name + data[0].desc, currentTime: time };
					var mapCover = { latitude: data[0].latitude, longitude: data[0].longitude, iconPath: '../../../static/img/location' };
					var tempList = that.list;
					// that.list.unshift(item);
					that.covers.push(mapCover);
					that.location = { latitude: data[0].latitude, longitude: data[0].longitude };
				}
			});
		},
		getDate(type) {
			const date = new Date();

			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();
			let h = date.getHours();
			let m = date.getMinutes();
			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;

			return `${year}-${month}-${day} ${h}:${m}`;
		},
		locationList() {
			this.$http.post('as/xagrid/appinspect/applylist', {}).then(ret => {
				if (ret.errcode == 0) {
					if (ret.data.results.length > 0) {
						let locationData = JSON.parse(ret.data.results[0].addressjson);
						let lData = [];
						for (let i = 0; i < 3; i++) {
							let item = { id: i + 1, address: locationData[i].address, latitude: locationData[i].latitude, longitude: locationData[i].longitude, checked: false };
							lData.push(item);
						}
						if (ret.data.results[0].approval_status == 1) {
							this.addressData = lData;
							this.state = 3;
						} else {
							this.addressData = lData;
							this.state = 2;
						}
					} else {
						console.log('data没有数据返回');
					}
				} else {
					uni.showToast({
						title: '联网出错，请从新进入页面',
						icon: 'none'
					});
				}
				if(this.state != 1) {
                    this.mapControls = []
                }else{
                    this.covers = []
                }
			});
		},
		createInpectApply(json) {
			let _this = this;
			this.$http.post('ac/xagrid/appInpectService/createInpectApply', { addressjson: JSON.stringify(json) }).then(ret => {
				console.log(ret);
				if(ret.errcode ==0){
					_this.locationList();
					uni.setStorageSync('addressjson',null)
				}else{
					uni.showToast({
						title:ret.errmsg,
						icon:'none'
					})
				}
			});
		},
		// 保存设置的数据到本地
		savePoitLock1(id) {
			let _this = this;
			try {
				let value = uni.getStorageSync('addressjson');
				if (value) {
					let json = JSON.parse(value);
					if (json.length >= 2) {
						this.getLocationInfo(function(data){
                            json.push({ id: id, address: data.address, latitude: data.latitude, longitude: data.longitude });
                            _this.createInpectApply(json);
                        })
					} else {
                      this.getLocationInfo(function(data){
								json.push({ id: id, address: data.address, latitude: data.latitude, longitude: data.longitude });
								_this.state = 1;
								uni.setStorageSync('addressjson', JSON.stringify(json));
								json.push({ id: 3, address: '等待设置' });
								_this.addressData = json;

						});
					}
				} else {
                  this.getLocationInfo(function(data){
							let j = [{ id: id, address: data.address, latitude: data.latitude, longitude: data.longitude }];
							_this.state = 1;
							uni.setStorageSync('addressjson', JSON.stringify(j));
							j.push({ id: 2, address: '等待设置' });
							j.push({ id: 3, address: '等待设置' });
							_this.addressData = j;

					});
				}
			} catch (e) {
				//TODO handle the exception
			}
		},
      savePoitLock(id) {
			let _this = this;
          uni.showLoading({
              title: '获取地址位置..'
          });
			try {
                this.getLocationInfo(function(data){
	                uni.hideLoading();
                    _this.addressData[id-1] = { id: id, address: data.address, latitude: data.latitude, longitude: data.longitude };
                    _this.state = 1;
                    uni.setStorageSync('addressjson', JSON.stringify(_this.addressData));
                });
			} catch (e) {
              uni.hideLoading();
            uni.showToast({
                title: '获取失败，请重试',
                icon: 'none'
            });
				//TODO handle the exception
			}
		},
        getLocationInfo(fun){
	        var self = this;
	        var mapContext = uni.createMapContext("mapId", this);
	        mapContext.getCenterLocation({
		        success(res) {
			        console.log('获取中心点' + JSON.stringify(res));
			        let point = new plus.maps.Point(res.longitude, res.latitude);
			        plus.maps.Map.reverseGeocode(
				        point,
				        {},
				        function(event) {
					        let address = event.address; // 转换后的地理位置
					        let point = event.coord; // 转换后的坐标信息
					        let coordType = event.coordType; // 转换后的坐标系类型
					        let reg = /.+?(省|市|自治区|自治州|县|区)/g;
					        let addressList = address
						        .match(reg)
						        .toString()
						        .split(',');
					        console.log(JSON.stringify(addressList))
                            let ss = '辽宁省'
                            let ad = address.replace(ss,'')
                          console.log(ad)
					        fun({longitude:res.longitude,latitude:res.latitude,address:ad})
				        },
				        function(e) {}
			        );
		        }
	        })
        },
		previewImage(index) {
			//预览图片
			uni.previewImage({
				current: this.imageList[index],
				urls: this.imageList
			});
		},
		close(e) {
			this.imageList.splice(e, 1);
		},
		chooseImg() {
			//选择图片
			uni.chooseImage({
				sourceType: ['camera'],
				sizeType: 'compressed',
				count: 6 - this.imageList.length,
				success: res => {
					this.imageList = this.imageList.concat(res.tempFilePaths);
					console.log(JSON.stringify(res));
				}
			});
		},
		daka() {
			let value = this.checkAddress;
			if (value.latitude == undefined) {
				uni.showToast({
					title: '请选择打卡位置',
					icon: 'none'
				});
				return false;
			}
			if (this.imageList.length > 0) {
				console.log('上传图片开始');
				this.uploadImages();
			} else {
				uni.showToast({
					title: '请先拍照',
					icon: 'none'
				});
				return false;
			}
			// preceedPointInArea();
		},
		// 打卡提交接口
		createInpect(){
			let detail = this.checkAddress
			let photo = this.upimageData
			let location = this.location
			this.$http.post('ac/xagrid/appInpectService/createInpect',{id:detail.id,longitude:location.longitude,latitude:location.latitude,photo:photo}).then(ret=>{
				console.log(JSON.stringify(ret),'打卡返回')
				if(ret.errcode == 0){
					uni.showToast({
						title:'打卡成功!',
						icon:'none'
					})
				}else{
					uni.showToast({
						title:ret.errmsg,
						icon:'none'
					})
				}
			})
		},
		radioChange(detail) {
			this.checkAddress = detail;
			this.current = detail.id
			console.log(this.current);
		},
		uploadImages() {
			var that = this;
			var oldImages = new Array();
			var images = new Array();
			console.log(JSON.stringify(that.imageList),'----dddd')
			for (var i = 0; i < that.imageList.length; i++) {
				var img = that.imageList[i];
				console.log('图片地址' + img);
				console.log('是否包含前缀' + img.indexOf('http://image.tripln.top/gridfile'));
				if (img.indexOf('http://image.tripln.top/gridfile') == 0) {
					oldImages.push(img.substr(32));
				} else {
					images.push({ name: 'images-' + String(i), uri: img });
				}
			}
			console.log('图片地址：' + JSON.stringify(images));
			console.log('header里的' + JSON.stringify(oldImages));
			if (images.length > 0) {
				uni.uploadFile({
					url: 'http://grid.tripln.top/api/xagrid/upload',
					files: images,
					fileType: 'image',
					header: that.uploadFileHeader,
					success: res => {
						// _contentResult = JSON.parse(res.data); //转义字符 得到结果集
						console.log('上传图片成功' + res.data);

						var succData = JSON.parse(res.data);
						for (var i = 0; i < succData.data.length; i++) {
							oldImages.push(succData.data[i].path);
						}
						console.log(' 整理后图片地址' + oldImages);
						that.upimageData = oldImages.join(',');
						console.log('参数' + JSON.stringify(that.upimageData));
						that.createInpect()
					},
					fail: err => {
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			}
		},
        setNewLocation(){
	        let value = uni.getStorageSync('addressjson');
	        if(value){
			    this.addressData = JSON.parse(value)
            }else{
			    this.addressData = [{ id: 1, address: '等待设置' },{ id: 2, address: '等待设置' },{ id: 3, address: '等待设置' }]
            }
            this.state = 1
	        this.setMapControls()
        },
        saveDaKa(){
	        let value = uni.getStorageSync('addressjson');
	        if(value){
                let json = JSON.parse(value);
                let go = false
                for (let i=0;i<3;i++){
                    if(!json[i].latitude){
                        go = true
                    }
                }
                if(go){
                    uni.showToast({
                        title:'三个地址都必须设置',
                        icon:'none'
                    })
                  return false
                }
                this.createInpectApply(json);
            }else{
                uni.showToast({
                    title:'三个地址都必须设置',
                    icon:'none'
                })
            }
        }
	}
};
</script>

<style>
.lyx-action {
	padding: 20upx;
}
.lya-action-top {
	font-size: 16px;
	font-weight: bold;
	border-bottom: 2upx solid #666666;
	margin-bottom: 20upx;
}
.uni-flex {
	margin-bottom: 8upx;
}
.viewBg {
	width: 100%;
	height: 100%;
	/* background-color: #0FAEFF; */
}

map {
	width: 100%;
	height: 600upx;
}

.contentView {
	display: flex;
	flex-direction: column;
	align-items: margin-left;
	margin-left: 20upx;
}
.resave-local {
    position: relative;
    bottom: 20upx;
    width: 100%;
    text-align: center;
    color: rgb(86, 185, 140);
}
.lyx-action .mini-btn{
	width: 85px;
}
</style>
